package com.dreamana.ui
{
	import com.dreamana.command.BaseCommand;
	
	import flash.display.Loader;
	import flash.events.Event;
	import flash.geom.Rectangle;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	
	public class SkinningCommand extends BaseCommand
	{
		private var _url:String;
		private var _loader:Loader;
		private var _pool:Object;
		
		
		public function SkinningCommand(xmlURL:String)
		{
			_url = xmlURL;
			_loader = new Loader();
			_pool = {};
		}
		
		override public function execute():void
		{
			//load xml
			loadXML(_url);
		}
		
		public function getClip(name:String):SkinClip
		{
			var clip:SkinClip = _pool[name];
			if(clip == null) {
				clip = new SkinClip(null, _loader);
				_pool[name] = clip;
			}
			return clip;
		}
		
		private function loadXML(url:String):void
		{
			var xmlloader:URLLoader = new URLLoader();
			xmlloader.addEventListener(Event.COMPLETE, onXMLLoaded);
			xmlloader.load(new URLRequest(url));
		}
		
		private function loadImage(url:String):void
		{
			_loader.load(new URLRequest(url));
		}
		
		private function onXMLLoaded(event:Event):void
		{
			var xmlloader:URLLoader = event.currentTarget as URLLoader;
			xmlloader.removeEventListener(Event.COMPLETE, onXMLLoaded);
			
			try {
				var xml:XML = new XML(xmlloader.data);
			}
			catch(e:Error) {
				trace(e.message);
				return;
			}
			
			var path:String = _url.substring(0, _url.lastIndexOf("/")+1) + xml.@imagePath;
			
			//set rects
			var xmllist:XMLList = xml.child("SubTexture");
			var num:int = xmllist.length();
			for(var i:int=0; i < num; ++i)
			{
				var item:XML = xmllist[i];
				
				var clip:SkinClip = _pool[item.@name];
				if(clip) {
					clip.rect = new Rectangle(item.@x, item.@y, item.@width, item.@height);
				}
			}
			
			//load image
			loadImage(path);
		}
		
		//--- GETTER/SETTERS ---
		public function set url(value:String):void { _url = value; }
		public function get url():String { return _url; }
		
		public function get loader():Loader { return _loader; }
	}
}